/**
 * File name: Bucket.java Author: Willard Wang Create date: Aug 23, 2013
 */
package edu.sjtu.se.prophet.graph;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * @author deathspeeder
 * 
 */
public class Bucket implements Serializable {
    private static Logger logger = Logger.getLogger(Bucket.class);

    /**
     * 
     */
    private static final long serialVersionUID = 6989815107130467935L;
    protected List<Node> data = new ArrayList<Node>();

    public List<Node> getData() {
        return data;
    }

    public void setData(List<Node> data) {
        this.data = data;
    }

    public boolean containsNode(String id) {
        for (Node node : data) {
            if (node.getId().equals(id))
                return true;
        }
        return false;
    }

    public boolean containsNode(Node target) {
        if (target == null)
            return false;
        else
            return containsNode(target.getId());
    }

    public void addAtFront(Node node) {
        data.add(0, node);
    }

    public float getAverageMetric(String metricName) {
        float sum = getSumMetric(metricName);
        return data.size() == 0 ? sum : sum / data.size();
    }

    public float getSumMetric(String metricName) {
        float sum = 0.0f;
        for (Node node : data) {
            if (node.getMetrics().containsKey(metricName)) {
                Object obj = node.getMetrics().get(metricName);
                float value = 0.0f;
                if (obj instanceof Integer)
                    value = (Integer) obj;
                else if (obj instanceof Float)
                    value = (Float) obj;
                else if (obj instanceof Double) {
                    double temp = (Double) obj;
                    value = (float) temp;
                }
                else
                    logger.error("Unkown value type " + obj.getClass());
                sum += value;
            }
        }
        return sum;
    }
}
